package cn.caijiapeng.spt.ctrl.admin;

import java.io.File;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.upload.ExceededSizeException;
import com.jfinal.upload.UploadFile;

import cn.caijiapeng.spt.bean.Resp;
import cn.caijiapeng.spt.config.WebConst;
import cn.caijiapeng.spt.interceptor.AdminInterceptor;
import cn.caijiapeng.spt.kit.ImageKit;
import cn.caijiapeng.spt.model.FeedBack;
import cn.caijiapeng.spt.model.SysAccess;
import cn.caijiapeng.spt.service.FeedBackService;
import cn.caijiapeng.spt.validate.FeedBackSaveValid;

public class FeedBackCtrl extends Controller{
	public void index() {
		Integer pageNumber = getParaToInt("pageNumber", 1);
		Integer pageSize = getParaToInt("pageSize", 20);
		renderJson(Resp.ok(FeedBackService.srv.getPage(pageNumber, pageSize)));
	}
	
	@Before(FeedBackSaveValid.class)
	public void save() {
		FeedBack fb = getModel(FeedBack.class, "", true);
		SysAccess access = getAttr(WebConst.LOGIN_SYS_ACCESS);
		fb.set("user_id", access.get("user_id"));
		if(FeedBackService.srv.save(fb)) {
			renderJson(Resp.ok());
		}else {
			renderJson(Resp.fail());
		}
	}
	
	@Clear(AdminInterceptor.class)
	public void uploadImg() {
		try {
			UploadFile file = getFiles("/images").get(0);
			if(!file.getFile().exists()) {
				renderJson(Resp.fail().set("msg", "上传失败").delete("message"));
				return;
			}
			File newFile = ImageKit.rename(file.getFile());
			renderJson(Resp.ok(Kv.by("title", "图片名称").set("src", "/upload/images/" + newFile.getName())));
		} catch (ExceededSizeException e) {
			renderJson(Resp.fail().set("msg", "图片大小限制在60KB以内").delete("message"));
		}
		
	}
	
	
}
